package com.lemon.exam.common.entity.system;

import com.lemon.exam.common.constant.ApiConst;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

/**
 * 登录用户信息
 *
 * @author Lemon
 * @since 2025/3/22 11:18
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {
    /**
     * 扩展字段
     */
    private Long id;//用户ID
    private String name;//姓名
    private List<String> roleList;//角色集合
    private List<String> resourceList;//权限集合
    /**
     * 默认字段
     */
    private String username;//登录名
    private String password;//密码
    private Boolean enabled;//状态

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (!CollectionUtils.isEmpty(roleList) && !CollectionUtils.isEmpty(resourceList)) {
            return Stream.concat(getRole(), getResource()).map(SimpleGrantedAuthority::new).toList();
        } else if (!CollectionUtils.isEmpty(roleList)) {
            return getRole().map(SimpleGrantedAuthority::new).toList();
        } else if (!CollectionUtils.isEmpty(resourceList)) {
            return getResource().map(SimpleGrantedAuthority::new).toList();
        } else {
            return Collections.emptyList();
        }
    }

    private Stream<String> getRole() {
        return roleList.parallelStream().map(item -> ApiConst.ROLE_PREFIX + item);
    }

    private Stream<String> getResource() {
        return resourceList.parallelStream().map(item -> ApiConst.RESOURCE_PREFIX + item.replaceAll("/", ":"));
    }
}
